package com.rfid.analysis;

import android.util.Log;

import com.rfid.protocol.Instruction;

import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.NonNull;

/**
 * @author Administrator
 * @date 2020/9/16
 */
public class  HandlerCommand extends Handler {

    private final List<Instruction> mCommandList;

    public HandlerCommand(@NonNull List<Instruction> commandList) {
        mCommandList = commandList;
    }

    @Override
    public void handleRequest(Message request) {
        if(logOpen) {
            Log.e("handleRequest", "进入HandlerCommand");
        }
        request.setCurrentNodeHandler(this);
        ByteBuffer byteBuffer = request.getBuffer();
        if (byteBuffer.position() + getLength() <= byteBuffer.limit()) {
            byte[] read = new byte[getLength()];
            byteBuffer.get(read);
            for (Instruction command : mCommandList) {
                if (Arrays.equals(command.getCommand(), read)) {
                    //读取成功
                    request.addData(read);
                    request.setCommand(command);
                    if (getNext() != null) {
                        getNext().handleRequest(request);
                    }
                    return;
                }
            }
            request.getFirstHandler().handleRequest(request);
        }else {
            //数据不完整，等待写入
            byteBuffer.compact();
        }

    }


    private int getLength() {
        return 2;
    }


}